var express = require("express");
const fs = require("fs");
var router = express.Router();

// length:46
const todayLuck = [
  "都说男人是大猪蹄子，可是我的小姐妹们啃的比谁都香",
  "明明可以靠颜值 偏偏却要工作 我不知道明明是谁反正我是偏偏",
  "别人发自拍300个赞，166条评论，底下都是帅哥，哥哥男神，我发自拍三个点赞两个评论，其中还有一个人说：这是你？",
  "今年我决定走走复古路线，穿去年的衣服，肯定不是因为没钱，我只是怀旧",
  "哈罗～！我趁主人睡觉偷偷发个自我介绍，我是小手机！(^O^)有别的小手机一起聊聊吗！(>^ω^<)",
  "我觉得我的男朋友还是有优点的 总结来说就是五个字：会挑女朋友",
  "世界上最令我难受的三件事：上班、 早起（为了去上班）、早睡（为了早起去上班）",
  "去买奶茶 店员问我要几分甜 我说跟我一样甜 店员说好的 然后给了我一杯柠檬水",
  "钱能不能买到快乐？我不知道，我现在很快乐，能不能卖钱？",
  "我真的不爽有人说着说着话还突然带一点英文 这样是真的很low",
  "我喜欢睡觉也是有原因的，因为床可以让我依靠，被子可以让我拥抱",
  "凡有我微信号者 可凭我的微信号 到附近超市领取冰激凌三箱 旺仔三箱 领取方式比较简单 直接拿起就跑 不要停留 吵架的事留给我",
  "别人处对象要处齐12星座，我不一样，我往百家姓上干",
  "成功源于后天的努力，所以今明两天就休息吧",
  "我的TIMI，闪现=移坟，名刀=晚死，金身=等死，复活甲=死了又死",
  "18岁 经济独立 全款买了个三明治 在走进教室那一刻 我被学生会抓住 再见 我的早餐",
  "我是女娲，我快热死了，给我转5块钱吃冰激凌，我给你捏个对象",
  "要和家境相仿的人一起玩 有没有一起要饭的",
  "天气热了，我不再是单身狗了，我是热狗",
  "这个天气挺尬的，不开空调又热，开的话还得去买一台",
  "我终于明白了一个道理：人丑就要多读书，难怪大家都说，一看我就不是读书的料",
  "天要再这么热下去，恐怕我冰淇淋的身份就要曝光了",
  "不要总说国产东西不好用 就比如说人民币 我就觉得很好用 我一直都在用 而且总觉得不够用",
  "上天给了我很多次变胖的机会我都成功抓住了",
  "如果你看不上我，就把眼睛捐给有需要的人吧",
  "和其他公主一样，每天都有骑士带着不同的吃的来看我，唯一不同的是，我的骑士要收配送费",
  "喝一杯奶茶吧 只要没人看见 就是0卡路里",
  "天气炎热，喜欢玩水的人朋友可以我家洗碗",
  "跟你聊天还不如跟客服聊天，不仅回复的快，还叫我亲爱的",
  "听说睡觉手机放在枕头旁边有辐射，吓得我赶紧起来把枕头扔了，吓死我了",
  "世界这么大，你不出去看看，就不知道有多热",
  "我只想做个与世无争的垃圾，没想到还要被分类",
  "今晚月色很美，风仿佛都会说话，他说“让一让，堵路了",
  "没钱用的时候跟我说，让我知道不止我一个人，没钱用",
  "可真是败家的孩子，上亿的家产，我一醒就没了",
  "你身上有她的香水味，一闻就没我的贵",
  "只有交话费的时候，才能感觉到我说的话，原来也那么值钱",
  "每天早上起床我都会看一眼富豪榜，如果上面没有我的名字，我就去上班，如果有，我就去看病",
  "你们每次骂别人时，有没有考虑过对方的感受？反正我是有，尽量不用方言，怕对方听不懂",
  "我怕麻烦说没下拼多多，他们更兴奋了，说新用户砍得多",
  "只有一番努力过后，你才能尝到放弃的快乐",
  "我们都是祖国的花朵，只不过有人长成了玫瑰，有些人长成了百合，而有些人长成了多肉",
  "刚称体重，发现我竟然瘦了100斤，仔细一看，才发现原来是一条腿忘记放上来了，无语，这一天天给我忙的",
  "多希望开学的时候，老师说一句，来就来嘛！还带什么作业，太客气了",
  "考完四级英语听力，我就悟出一个道理，有些话，只能说给懂的人听",
  "听说每个中国人平均每天摸150次手机，我笑了，净扯淡，明明就一次，睡醒拿起，睡前放下",
];

// 期待数据路径
const expectPath = "./interface/self/expect.txt";

// 游记数据路径
const visitPath = "./interface/self/visit.txt";

// 获取类型数据路径
const typePath = "./interface/self/type.txt";

// 我的标签路径
const tagsPath = "./interface/self/tags.txt";
/**
 *
 *   存储文件 数据类型
 *    {
 *      selectOption:[ {id, key, desc} ], // select的option数据
 *      eventsData:[{ id, type, date, startTime, endTime, duration }], // 所有的日程数据添加在此  {duration: 持续时间}
 *    }
 */

/**
 *
 * @param {*} obj
 * {
 *    selectOption: [],
 *    eventObj: {  key1:[], key2:[]  }
 * }
 */
// 写文件  || 创建并写入
/*
  返回值有两个状态:
    success:   创建 | 写入成功
    error:     创建 | 写入失败
*/
const writeFile = (obj, path = typePath) => {
  const writeContent = JSON.stringify({ file: obj });
  console.log("需要写入的数据", writeContent);

  try {
    fs.writeFileSync(path, writeContent);
    return "success";
  } catch (error) {
    return "error";
  }
};

// 读取文件
readFile = (path = typePath) => {
  try {
    const data = fs.readFileSync(path, "utf8");
    return data;
  } catch (error) {
    return "读取失败";
  }
};

// 获取select的下拉框参数
router.get("/selectOption", function (request, response) {
  const readData = readFile();
  console.log("读取结果", readData);
  let selectOption = [];
  if (readData != "读取失败") {
    selectOption = JSON.parse(readData).file.selectOption || [
      {
        id: 1,
        key: "study",
        desc: "学习",
      },
      {
        id: 2,

        key: "sport",
        desc: "运动",
      },
    ];
  }
  console.log("selectOption: ", selectOption);

  let res = {
    code: 200,
    data: selectOption,
  };
  response.send(res);
});

// 添加一个事件
// 将最新的事件 添加在最前面
router.post("/event/add", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  console.log("获取post参数", reqData);
  let resStatus = {
    code: 481,
    data: null,
    msg: "添加事件失败",
  };

  // 需要写入文件
  // 首先要获取原来数据
  const readData = readFile();
  console.log("读取结果", readData);

  // == 读取失败 代表文件不存在  可直接写入
  if (readData == "读取失败") {
    const key = reqData.selectValue;
    let eventObj = {};
    eventObj[key] = [{ id: 1, ...reqData }];
    console.log("eventObj: ", eventObj);
    const writeObj = {
      selectOption: [],
      eventObj,
    };
    const writeBool = writeFile(writeObj);
    if (writeBool) {
      resStatus = {
        code: 200,
        msg: "添加成功",
        data: null,
      };
    }
  } else {
    // 此时代表文件存在
    const parseReadData = JSON.parse(readData).file;
    console.log("parseReadData: ", parseReadData.eventObj);

    let eventObj = parseReadData.eventObj;
    console.log("读取成功", eventObj);

    let writeObj = {}; // 需要写入的数据
    if (!eventObj || JSON.stringify(eventObj) == "{}") {
      // 此时代表eventObj不存在 或者数据为空
      writeObj = {
        selectOption: parseReadData.selectOption || [],
        eventObj: [{ id: 1, ...reqData }],
      };
    } else {
      /**
       * eventObj:{key1:[{item}], key2:[]}
       */

      /**
       * reqData: {item}
       */
      // Object.keys(eventObj)
      //  如果key存在，直接追加
      if (Object.keys(eventObj).includes(reqData.selectValue)) {
        const id = eventObj[reqData.selectValue].length + 1;
        eventObj[reqData.selectValue] = [
          { id, ...reqData },
          ...eventObj[reqData.selectValue],
        ];
      } else {
        // 如果key不存在 直接添加
        eventObj[reqData.selectValue] = [{ id: 1, ...reqData }];
      }

      // 代表eventObj有数据，需要追加
      writeObj = {
        selectOption: parseReadData.selectOption || [],
        eventObj: { ...eventObj },
      };
    }

    const writeBool = writeFile(writeObj);
    if (writeBool) {
      resStatus = {
        code: 200,
        msg: "添加成功",
        data: null,
      };
    }
  }

  response.send(resStatus);
});

// 所有事件  返回值
function allEvent(eventObj, selectOption) {
  return () => {
    var resData = [];
    console.log("- - - - - - -  - - - -  -");
    // key值集合
    let allKey = [];
    selectOption.forEach((element) => {
      allKey.push(element.key);
    });

    console.log("all * * * * keys", allKey);

    // 返回的数据需要分类

    eventObj.map((eventItem) => {
      console.log("eventItem", eventItem);
      const key = eventItem.selectValue;
      if (!resData[key]) {
        resData[`${key}`] = [eventItem];
      } else {
        resData[key] = [eventItem, ...resData[key]];
      }
      console.log("+ + + + + ");
    });

    console.log("resData - - - - - ", resData);
    return resData;
  };
}

// 获取所有事件
router.get("/event/get", function (request, response) {
  const readData = readFile();
  let resStatus = {
    code: 482,
    msg: "读取事件失败",
    data: null,
  };
  // 读取文件成功
  if (readData != "读取失败") {
    let file = JSON.parse(readData).file;
    let eventObj = file.eventObj;

    resStatus = {
      code: 200,
      msg: "读取事件成功",
      data: eventObj,
    };
  }
  response.send(resStatus);
});

// 删除某事件
router.post("/event/delete", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  const { type, id } = reqData;
  // console.log("获取post参数", reqData);

  const readData = readFile();
  const file = JSON.parse(readData).file;
  const eventObj = file.eventObj || {};
  // console.log("eventObj: ", eventObj);

  // 当前休要操作的数据对象
  let curType = eventObj[type];
  curType = curType.filter((event) => event.id != id);

  // console.log("curType:  过滤后的数据 ", curType);

  const newEventObj = {
    ...eventObj,
  };
  newEventObj[type] = curType;
  const writeObj = {
    ...file,
    eventObj: { ...newEventObj },
  };
  console.log("writeObj: ", writeObj);
  let resStatus = {
    code: 483,
    data: {},
    msg: "删除事件失败",
  };

  if (writeFile(writeObj) == "success") {
    resStatus = {
      code: 200,
      msg: "删除成功",
      data: null,
    };
  }
  response.send(resStatus);
});

// 修改某事件
router.post("/type/add", function (request, response) {
  // 获取post参数
  const { key, desc } = request.body;
  console.log("key,desc: ", key, desc);

  const readData = readFile();
  const file = JSON.parse(readData).file;
  const selectOption = file.selectOption || [];
  const id = selectOption.length == 0 ? 1 : selectOption.length + 1;
  const newSelectOption = [
    ...selectOption,
    {
      id,
      key,
      desc,
    },
  ];
  console.log("newSelectOption: ", newSelectOption);

  let resStatus = {
    code: 485,
    data: null,
    msg: "添加类型失败",
  };

  const writeObj = {
    ...file,
    selectOption: newSelectOption,
  };
  if (writeFile(writeObj) == "success") {
    resStatus = {
      code: 200,
      data: null,
      msg: "添加类型成功",
    };
  }

  response.send(resStatus);
});

// 获取tags
router.get("/tags/get", function (request, response) {
  const readData = readFile(tagsPath);
  console.log("readData", readData);
  const tags = readData != "读取失败" ? JSON.parse(readData).file : null;
  const res = {
    code: 200,
    data: tags || null,
  };
  response.send(res);
});

// 添加tag
router.post("/tags/add", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  const readData = readFile(tagsPath);
  console.log("readData - - - ", typeof readData);
  let writeData = [];

  // 组装写入数据
  if (readData == "读取失败") {
    writeData = [{ id: 1, ...reqData }];
  } else {
    const tags = JSON.parse(readData).file;
    const length = tags.length || 0;
    const id = length != 0 ? tags[0].id + 1 : 1;

    writeData = [{ id, ...reqData }, ...tags];
  }
  let resStatus = {
    code: 486,
    data: null,
    msg: "添加标签失败",
  };

  // 进行写入
  if (writeFile(writeData, tagsPath) == "success") {
    resStatus = {
      code: 200,
      data: null,
      msg: "添加标签成功",
    };
  }

  response.send(resStatus);
});

// 删除tag
router.post("/tags/delete", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  console.log("获取到的参数reqData: ", reqData);
  const readData = readFile(tagsPath);
  let writeData = [];

  let resStatus = {
    code: 487,
    data: null,
    msg: "删除标签失败",
  };

  // 组装写入数据
  if (readData !== "读取失败") {
    const tags = JSON.parse(readData).file;
    console.log("tags: ", typeof tags);
    writeData = tags.filter((tag) => tag.id !== reqData.id);
    // 进行写入
    if (writeFile(writeData, tagsPath) == "success") {
      resStatus = {
        code: 200,
        data: null,
        msg: "删除标签成功",
      };
    }
  }
  response.send(resStatus);
});

// 读取事件
router.get("/interesting", function (request, response) {
  console.log("todayLuck;", todayLuck.length);
  response.send({
    code: 200,
    msg: todayLuck[Math.floor(Math.random() * todayLuck.length)],
  });
});

// 添加游记
router.post("/visitor/add", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  // console.log("获取post参数", reqData);

  const readData = readFile(visitPath);
  let writeData = [];
  if (readData == "读取失败" || readData == "") {
    writeData = [reqData];
  } else {
    let fileData = JSON.parse(readData).file ? JSON.parse(readData).file : [];
    const index = fileData.findIndex((item) => item.id == reqData.id);
    if (index > -1) {
      fileData.forEach((item) => {
        if (item.id == reqData.id) return writeData.push(reqData);
        return writeData.push(item);
      });
    } else {
      writeData = [{ ...reqData }, ...fileData];
    }
  }

  let resStatus = {
    code: 491,
    data: [],
    msg: "添加游记失败",
  };

  if (writeFile(writeData, visitPath) == "success") {
    resStatus = {
      code: 200,
      data: {},
      msg: "添加游记成功",
    };
  }

  response.send(resStatus);
});

// 获取游记
router.get("/visitor/get", function (request, response) {
  const readData = readFile(visitPath);
  console.log("readData: ", readData);

  let resStatus = {
    code: 492,
    data: [],
    msg: "读取游记失败",
  };
  if (readData != "" && readData != "读取失败") {
    resStatus = {
      code: 200,
      data: JSON.parse(readData).file,
      msg: "读取游记成功",
    };
  }
  response.send(resStatus);
});

// 删除游记
router.post("/visitor/delete", function (request, response) {
  // 获取post参数
  const reqData = request.body;

  const readData = readFile(visitPath);
  let writeData = [];
  if (readData != "读取失败" && readData != "") {
    let fileData = JSON.parse(readData).file || [];
    console.log("fileData: ", fileData.length);
    writeData = fileData.filter((item) => item.id !== reqData.id);
  }

  console.log("需要写入", writeData.length);

  let resStatus = {
    code: 495,
    data: [],
    msg: "删除游记失败",
  };

  if (writeFile(writeData, visitPath) == "success") {
    resStatus = {
      code: 200,
      data: null,
      msg: "删除游记成功",
    };
  }

  response.send(resStatus);
});

// 添加期待
router.post("/target/add", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  console.log("获取post参数", reqData);

  const readData = readFile(expectPath);
  console.log("readData: -", readData);
  let writeData = [];
  if (readData === "读取失败" || readData.length === 0) {
    writeData = [{ ...reqData }];
  } else {
    console.log("else");
    let fileData = JSON.parse(readData).file ? JSON.parse(readData).file : [];
    const index = fileData.findIndex((item) => item.id == reqData.id);
    if (index > -1) {
      fileData.forEach((item) => {
        if (item.id == reqData.id) return writeData.push(reqData);
        return writeData.push(item);
      });
    } else {
      writeData = [{ ...reqData }, ...fileData];
    }
  }
  console.log("writeData: ", writeData);

  let resStatus = {
    code: 493,
    data: {},
    msg: "添加期待失败",
  };

  if (writeFile(writeData, expectPath) == "success") {
    resStatus = {
      code: 200,
      data: null,
      msg: "添加期待成功",
    };
  }
  response.send(resStatus);
});

// 删除期待
router.post("/target/delete", function (request, response) {
  // 获取post参数
  const reqData = request.body;
  console.log("获取post参数", reqData);

  const readData = readFile(expectPath);
  let writeData = [];
  if (readData != "读取失败" && readData != "") {
    let fileData = JSON.parse(readData).file || [];
    console.log("fileData: ", fileData);
    writeData = fileData.filter((item) => item.id !== reqData.id);
  }

  console.log("需要写入", writeData);

  let resStatus = {
    code: 496,
    data: [],
    msg: "删除期待失败",
  };

  if (writeFile(writeData, visitPath) == "success") {
    resStatus = {
      code: 200,
      data: null,
      msg: "删除期待成功",
    };
  }

  response.send(resStatus);
});

// 读取期待
router.get("/target/get", function (request, response) {
  const readData = readFile(expectPath);
  console.log("readData: ", readData);
  let resStatus = {
    code: 494,
    data: [],
    msg: "读取期待失败",
  };
  if (readData != "" && readData != "读取失败") {
    resStatus = {
      code: 200,
      data: JSON.parse(readData).file,
      msg: "读取期待成功",
    };
  }
  response.send(resStatus);
});

// router.post("/event/add", function (request, response) {
//   // 获取post参数
//   const reqData = request.body;
//   console.log("获取post参数", reqData);

//   let resStatus = {
//     code: 481,
//     data: {},
//     msg: "添加事件失败",
//   };

//   response.send(resStatus);
// });

// 读取事件
// router.get("/get", function (request, response) {
//   let resStatus = {
//     code: 481,
//     data: {},
//     msg: "获取失败",
//   };
//   response.send(resStatus);
// });
module.exports = router;
